import hashlib
import threading
import datetime
import random
import sys
import traceback
import pycurl
from cStringIO import StringIO

class ThreadClass(threading.Thread):
    def __init__(self, counter):
        self.count = counter
        threading.Thread.__init__(self)
    
    def run(self):
        reqs = []
        m = pycurl.CurlMulti()
        partnerId = random.randrange(50000, 50005)
        for i in range(self.count):
            response = StringIO()
            random.seed()
            hash = random.getrandbits(128)
            c = pycurl.Curl()
            url = "http://localhost/%s/%016x" % (partnerId, hash) 
            c.setopt(pycurl.URL, url)
            #c.setopt(pycurl.WRITEFUNCTION, response.write)
            #req = (sys_no, response, c)
            req = (None, response, c)
#            print "[%s] %s - (%s) %016x" % (self.getName(), now, partnerId, hash)
            m.add_handle(req[2])
            reqs.append(req)

        SELECT_TIMEOUT = 1.0
	num_handles = len(reqs)
	while num_handles:
    	    ret = m.select(SELECT_TIMEOUT)
    	    if ret == -1:
                continue
    	    while 1:
                ret, num_handles = m.perform()
                if ret != pycurl.E_CALL_MULTI_PERFORM:
                    break
        
        print "[%s] %s" % (self.getName(), len(reqs))
	#for req in reqs:
    	    #print req[1].getvalue() #contains response content
 


threads = 10
calls = 10
for i in range(threads):
    t = ThreadClass(calls)
    t.start()
